package JAVA并发;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author zhangmin
 * @create 2022-03-15 20:56
 *
 * 3、ForkJoin：主要用于并行计算中，和 MapReduce 原理类似，都是把大的计算任务拆分成多个小任务并行计算。继承RecursiveTask
 */
public class ForkJoinExample8 extends RecursiveTask<Integer> {
    //任务需要划分到比threshold小的时候才开始并行计算
    private final int threshold=5;
    private  int first;
    private int last;

    public ForkJoinExample8(int first,int last){
        this.first=first;
        this.last=last;
    }

    @Override
    protected Integer compute() {
        int res=0;
        if(last-first<=threshold){
            //任务足够小
            for (int i = first; i <= last; i++) {
                res+=i;
            }
        }else {
            //拆分任务
            int mid=first+(last-first)/2;
            ForkJoinExample8 left=new ForkJoinExample8(first,mid);
            ForkJoinExample8 right=new ForkJoinExample8(mid+1,last);
            left.fork();
            right.fork();
            res=left.join()+right.join();
        }
        return res;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinExample8 e=new ForkJoinExample8(1,100);
        //ForkJoin 使用 ForkJoinPool 来启动，它是一个特殊的线程池，线程数量取决于 CPU 核数。
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        Future res=forkJoinPool.submit(e);
        System.out.println(res.get());
    }
}
